﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;

namespace NanoMvvm
{
    public class AggregateCommand : CommandBase
    {
        public AggregateCommand(IEnumerable<ICommand> commands)
        {
            Commands = commands;
        }

        protected IEnumerable<ICommand> Commands { get; private set; }

        private volatile bool allMustExecuteCondition;
        public bool AllMustExecuteCondition
        {
            get { return allMustExecuteCondition; }
            set { allMustExecuteCondition = value; }
        }

        protected override void Execute(object parameter)
        {
            if (AllMustExecuteCondition)
            {
                foreach (var command in Commands)
                {
                    command.Execute(parameter);
                }
            }
            else
            {
                foreach (var command in Commands.Where(command => command.CanExecute(parameter)))
                {
                    command.Execute(parameter);
                }

            }
        }

        protected override bool CanExecute(object parameter)
        {
            return AllMustExecuteCondition ? Commands.All(cmd => cmd.CanExecute(parameter)) : Commands.Any(cmd => cmd.CanExecute(parameter));
        }
    }
}